package com.hzit.mmcb.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hzit.common.exception.Assert;
import com.hzit.common.result.ResponseEnum;
import com.hzit.mmb.base.utils.JwtUtils;
import com.hzit.mmcb.core.enums.BorrowInfoStatusEnum;
import com.hzit.mmcb.core.enums.BorrowerStatusEnum;
import com.hzit.mmcb.core.enums.UserBindEnum;
import com.hzit.mmcb.core.pojo.dto.BorrowerDetailDTO;
import com.hzit.mmcb.core.pojo.entity.*;
import com.hzit.mmcb.core.mapper.BorrowInfoMapper;
import com.hzit.mmcb.core.pojo.vo.BorrowInfoApprovalVO;
import com.hzit.mmcb.core.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sun.xml.bind.v2.model.core.ID;
import com.sun.xml.internal.ws.policy.AssertionSet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 借款信息表 服务实现类
 * </p>
 *
 * @author ljh
 * @since 2024-08-27
 */
@Service
public class BorrowInfoServiceImpl extends ServiceImpl<BorrowInfoMapper, BorrowInfo> implements BorrowInfoService {

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private IntegralGradeService integralGradeService;
    @Autowired
    private BorrowerService borrowerService;
    @Autowired
    private LendService lendService;
    /**
     * 根据用户id查询贷款申请状态
     * @param userId
     * @return
     */
    @Override
    public Integer getBorrowInfoStatus(Long userId) {
        List<BorrowInfo> borrowInfos = this.list(new LambdaQueryWrapper<BorrowInfo>().eq(BorrowInfo::getUserId, userId));
        if (borrowInfos.size()==0){
            return 0;
        }
        return borrowInfos.get(0).getStatus();
    }

    /**
     * 提交表单
     * @param borrowInfo
     * @param token
     */
    @Override
    public void saveByForm(BorrowInfo borrowInfo, String token) {
        Long userId = JwtUtils.getUserId(token);
        UserInfo userInfo= userInfoService.getById(userId);

        Assert.isTrue(userInfo.getBindStatus()== UserBindEnum.BIND_OK.getStatus(), ResponseEnum.USER_NO_BIND_ERROR);
        Assert.isTrue(userInfo.getBorrowAuthStatus()== BorrowerStatusEnum.AUTH_OK.getStatus(),ResponseEnum.USER_NO_AMOUNT_ERROR);
        Integer integral = userInfo.getIntegral();
        LambdaQueryWrapper<IntegralGrade> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.ge(IntegralGrade::getIntegralEnd,integral)
                .le(IntegralGrade::getIntegralStart,integral);
        IntegralGrade integralGradeServiceOne = integralGradeService.getOne(lambdaQueryWrapper);
        Assert.isTrue(integral.doubleValue()<integralGradeServiceOne.getBorrowAmount().doubleValue(),ResponseEnum.USER_AMOUNT_LESS_ERROR);
        borrowInfo.setUserId(userId);
        borrowInfo.setStatus(BorrowInfoStatusEnum.CHECK_RUN.getStatus());
        borrowInfo.setBorrowYearRate(borrowInfo.getBorrowYearRate().divide(new BigDecimal(100)));
        this.save(borrowInfo);
    }

    /**
     * 查询列表信息，包括补充信息
     * @return
     */
    @Override
    public List<BorrowInfo> listAll() {
        List<BorrowInfo> list = this.baseMapper.selectBorrowInfo();
        list.forEach(bi->{
            String returnMethod = borrowerService.getDictName(bi.getReturnMethod(), "returnMethod");
            String moneyUse = borrowerService.getDictName(bi.getMoneyUse(), "moneyUse");
            bi.getParam().put("returnMethod",returnMethod);
            bi.getParam().put("moneyUse",moneyUse);
            bi.getParam().put("status",BorrowInfoStatusEnum.getMsgByStatus(bi.getStatus()));

        });
        return list;
    }

    /**
     * 使用id查询借款人信息
     * @param id
     * @return
     */
    @Override
    public Map<String, Object> show(Integer id) {
        //查询借款信息
        BorrowInfo bi = this.getById(id);
        String returnMethod = borrowerService.getDictName(bi.getReturnMethod(), "returnMethod");
        String moneyUse = borrowerService.getDictName(bi.getMoneyUse(), "moneyUse");
        bi.getParam().put("returnMethod",returnMethod);
        bi.getParam().put("moneyUse",moneyUse);
        bi.getParam().put("status",BorrowInfoStatusEnum.getMsgByStatus(bi.getStatus()));

        //查询借款人信息
        Borrower borrower = borrowerService.getOne(new LambdaQueryWrapper<Borrower>().eq(Borrower::getUserId, bi.getUserId()));
        BorrowerDetailDTO borrowerDetailDTO = borrowerService.getDetailById(borrower.getId().intValue());
        Map<String,Object> map=new HashMap<>();
        map.put("borrowInfo",bi);
        map.put("borrower",borrowerDetailDTO);
        return map;
    }

    /**
     * 审核完成后的信息修改
     * @param vo
     */
    @Override
    public void approval(BorrowInfoApprovalVO vo) {
        BorrowInfo borrowInfo = this.getById(vo.getId());
        borrowInfo.setStatus(vo.getStatus());
        this.updateById(borrowInfo);
        if (borrowInfo.getStatus()==-1){
            return;
        }
        //标的设置
        lendService.createLend(vo,borrowInfo);
    }

}
